import axios from 'axios';

// 创建axios实例
const instance = axios.create();

// 请求拦截器：自动为每个请求加上Authorization头（如果有token）
instance.interceptors.request.use(config => {
  // 从localStorage获取token
  const token = localStorage.getItem('token');
  console.log('Request interceptor - token:', token); // 调试信息
  if (token) {
    // 按后端要求格式加上Bearer前缀
    config.headers['Authorization'] = 'Bearer ' + token;
    console.log('Request interceptor - Authorization header set'); // 调试信息
  } else {
    console.log('Request interceptor - no token found'); // 调试信息
  }
  return config;
}, error => Promise.reject(error));

// 响应拦截器：处理token过期等情况
instance.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    console.log('Response interceptor - error:', error.response?.status); // 调试信息
    if (error.response?.status === 401) {
      console.log('Token expired or invalid, redirecting to login'); // 调试信息
      // 清除token并跳转到登录页
      localStorage.removeItem('token');
      localStorage.removeItem('refreshToken');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

export default instance; 